//
//  StatusView.m
//  leerHealth
//
//  Created by ye on 2019/6/17.
//  Copyright © 2019年 yml. All rights reserved.
//

#import "StatusView.h"


@interface StatusView()
@property (nonatomic,  strong) UIWindow *overlayWindow;
@property (nonatomic,  strong) UIWindow *topWindow;
@property (nonatomic, strong) UILabel *titleLabel;
/// 关闭倒计时
@property (nonatomic,strong) NSTimer *popupItemTimer;
@end

static StatusView *sharedView;

@implementation StatusView

+ (StatusView*)sharedView
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedView = [[StatusView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//        sharedView.alpha = 0;
    });
    return sharedView;
}

+ (void)showWithStatus:(NSString *)status complented:(complented)complented{
    [[StatusView sharedView] setStatus:status complented:complented isCenter:false];
}

+ (void)showWithStatus:(NSString *)status
{
    [[StatusView sharedView] setStatus:status complented:nil isCenter:false];
}
+ (void)showCenterWithStatus:(NSString *)status
{
    [[StatusView sharedView] setStatus:status complented:nil isCenter:true];
}
- (NSTimer *)popupItemTimer
{
    if (!_popupItemTimer) {
        _popupItemTimer = [NSTimer scheduledTimerWithTimeInterval:0
                                                            target:self
                                                          selector:@selector(closeView)
                                                          userInfo:nil
                                                           repeats:NO];
    }
    return _popupItemTimer;
}
- (void)closeView{
    
    dispatch_async(dispatch_get_main_queue(), ^{
//            NSLog(@"回到主线程");
        [UIView transitionWithView:sharedView duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            
            [sharedView setAlpha:0.6];
            
        } completion:^(BOOL finished) {
            
            [sharedView removeFromSuperview];
            
        }];
        
        });
    
 
}
- (void)setStatus:(NSString*)status complented:(complented)complented isCenter:(BOOL)isCenter
{
    
    [self.overlayWindow addSubview:sharedView];

    [self.popupItemTimer invalidate];//释放
    self.popupItemTimer = nil;
    [self.popupItemTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:2]]; //开启

//    if(self.topWindow.subviews){
//
//    }
//    BOOL flag = false;
//    for (UIView *subview in keyWindow.subviews) {
//        if([subview isKindOfClass:MJReplaceAlertView.class]){
//            flag = true;
//        }
//    }

    self.titleLabel.text = status;
    CGFloat titleLabelH = 48;

    //超过60%换行
    CGFloat titleLabelWidth = [self.titleLabel sizeThatFits:CGSizeMake(MAXFLOAT, titleLabelH)].width;
    CGFloat normal_width = SCREEN_WIDTH*0.7;
    
    CGFloat titleLabelW = [self.titleLabel sizeThatFits:CGSizeMake(MAXFLOAT, titleLabelH)].width + 38;
    if(titleLabelWidth > normal_width){
        titleLabelW = normal_width;
    }else{
        titleLabelW = titleLabelWidth + 38;
    }
    
//    CGFloat titleLabelH_S = [self.titleLabel sizeThatFits:CGSizeMake(titleLabelW, MAXFLOAT)].height + 30;
    self.titleLabel.numberOfLines = 0;

    CGFloat statusY = SCREEN_HEIGHT/4*3;
    CGFloat statusX = (SCREEN_WIDTH - titleLabelW)/2.0;
    
    if(isCenter){
        statusY = SCREEN_HEIGHT/2;
    }

    sharedView.frame = CGRectMake(statusX, statusY, titleLabelW, titleLabelH);
    self.titleLabel.frame = sharedView.bounds;
    
    [sharedView addSubview:self.titleLabel];
    
    [sharedView setAlpha:1];

    [sharedView mj_dropShadowWithOffset:CGSizeMake(0, 3)
                         cornerRadius:5
                               radius:6
                                 color:[MJUIColorFromHex(0x48E3EB) colorWithAlphaComponent:0.43]
                                     opacity:1];
    
    [sharedView setAlpha:0];
    //渐变出现
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [sharedView setAlpha:1];
    } completion:^(BOOL finished) {
        
    }];
    
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = MJUIFontMake(14);
        titleLabel.text = @"";
        titleLabel.backgroundColor = [MJUIColorFromHex(0x000000) colorWithAlphaComponent:0.8];
        titleLabel.mj_cornerRadius = 24;
        titleLabel.textColor = UIColor.whiteColor;
        _titleLabel = titleLabel;
    }
    return _titleLabel;
}
- (void)xxsetStatus:(NSString*)status complented:(complented)complented isCenter:(BOOL)isCenter
{
    [sharedView removeFromSuperview];
    sharedView = [[StatusView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    CGFloat statusLH = 31;
    CGFloat statusLW = [status boundingRectWithSize:CGSizeMake(MAXFLOAT, statusLH) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.5]} context:nil].size.width + 40;
    CGFloat statusX = SCREEN_WIDTH/2.0 - statusLW/2.0;
    UIView *statusL = [[UIView alloc]initWithFrame:CGRectMake(0, 0, statusLW, statusLH)]; //SCREEN_HEIGHT
    statusL.backgroundColor = UIColor.mj_lightAppColor;
    statusL.layer.cornerRadius = statusLH/2;
    statusL.clipsToBounds = YES;
    statusL.layer.borderWidth = 1.f;
    statusL.layer.borderColor = [UIColor mj_colorWithHexString:@"#B2E1E4"].CGColor;
    
    CAGradientLayer *_gradientLayer = [CAGradientLayer layer];


    
    UILabel *lbl = [[UILabel alloc] initWithFrame:statusL.bounds];
    lbl.textColor = [UIColor mj_appColor];
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:12];
    lbl.text = status;
    [statusL addSubview:lbl];
    
    CGFloat statusY = SCREEN_HEIGHT/4*3;
    if(isCenter){
        statusY = SCREEN_HEIGHT/2;
    }
    sharedView.frame = CGRectMake(statusX, statusY, statusLW, statusLH);
    UIView *container = [[UIView alloc] initWithFrame:sharedView.bounds];
    container.clipsToBounds = true;
    [container addSubview:statusL];
    
    [sharedView addSubview:container];
    
//    [self.overlayWindow addSubview:sharedView];
    [self.topWindow addSubview:sharedView];

    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        statusL.frame = CGRectMake(0, 0, statusLW, statusLH);
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView transitionWithView:sharedView duration:0.3 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                [statusL setAlpha:0.6];
            } completion:^(BOOL finished) {
                [statusL removeFromSuperview];
                [sharedView removeFromSuperview];
                if (complented) {
                    complented(true);
                }
            }];
        });
    }];
}

#pragma mark - Getters

- (UIWindow *)overlayWindow {
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }
    _overlayWindow = window;
    return _overlayWindow;
}
//最顶层视图
- (UIWindow *)topWindow {
    
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (id windowView in windows) {
        NSString *viewName = NSStringFromClass([windowView class]);
        //键盘
        if ([@"UIRemoteKeyboardWindow" isEqualToString:viewName]) {
            window = windowView;
           break;
        }
    }
    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }
    _topWindow = window;
    return _topWindow;
}
@end
